import React, { Component } from 'react'
import '../assets/styles/login/login.less'
import logo from '../assets/images/logo.png'
import LogoImage from '../components/KImage'
import KInput from '../components/KInput';
import KButton from '../components/KButton';
import { hashHistory } from 'react-router'
import { connect } from 'react-redux';
import { Toast } from 'antd-mobile'

class Login extends Component {
    constructor(props) {
        super(props)
        this.state = {
            username: '',
            password: ''
        }
    }
    loginBtnClick() {
        // 要获取到 用户名和密码进行判断
        // 从store里面拿出 users ，跟 当前用户输入的 username和password 进行判断
        let users = this.props.users
        // 拿到用户名和密码
        // console.log(this.state.username, this.state.password);
        // 判断 users 里面有没有 对应的用户
        let has = users.some(e => e.username === this.state.username && e.password === this.state.password)
        if (has) {
            // 登录成功
            Toast.success('登录成功', 1, () => {
                // 手动跳转到 home 页面
                hashHistory.push('/home')
            })
        } else {
            // 提示用户
            Toast.fail('登录失败', 1)
        }
    }
    userNameChange(event) {
        this.setState({
            username: event.target.value
        })
    }
    passwordChange(event) {
        this.setState({
            password: event.target.value
        })
    }
    freeReg() {
        // 得到 用户名和 密码
        let username = this.state.username
        let password = this.state.password
        // 把数据写入store里面
        this.props.reg({ username, password })
    }
    render() {
        return (
            <div className="login-box">
                <LogoImage src={logo} style={{ textAlign: 'center' }} />
                <KInput onChange={this.userNameChange.bind(this)} value={this.state.username} icon="icon-shouji" placeholder="账号" className="mt20" />
                <KInput onChange={this.passwordChange.bind(this)} value={this.state.password} type="password" icon="icon-mima" placeholder="密码" className="mt20" />
                <KButton className="mt20" onClick={this.loginBtnClick.bind(this)}>登录</KButton>
                {/* <p>忘记密码</p> */}
                <KButton type="primary" className="mt20">忘记密码</KButton>
                <div className="btns mt20">
                    <KButton onClick={this.freeReg.bind(this)} style={{ width: '48%' }}>免费注册</KButton>
                    <KButton style={{ width: '48%' }}>游客登录</KButton>
                </div>
            </div>
        )
    }
}

const mapStateToProps = state => {
    console.log(state);
    return {
        users: state.users
    }
}

const mapDispatchToProps = dispatch => {
    return {
        reg(user) {
            const action = {
                type: 'reg',
                value: user
            }
            dispatch(action)
        }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Login)
